import Header from "@/components/header";
import { ThemeProvider } from "@/components/theme-provider";
import { Toaster } from "@/components/ui/sonner";
{{#if (eq api "orpc")}}
import { link, orpc } from "@/utils/orpc";
import type { QueryClient } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { useState } from "react";
import { createTanstackQueryUtils } from "@orpc/tanstack-query";
import type { AppRouterClient } from "@{{projectName}}/api/routers/index";
import { createORPCClient } from "@orpc/client";
{{/if}}
{{#if (eq api "trpc")}}
import type { trpc } from "@/utils/trpc";
import type { QueryClient } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
{{/if}}
import {
  HeadContent,
  Outlet,
  createRootRouteWithContext,
} from "@tanstack/react-router";
import { TanStackRouterDevtools } from "@tanstack/react-router-devtools";
import "../index.css";

{{#if (eq api "orpc")}}
export interface RouterAppContext {
  orpc: typeof orpc;
  queryClient: QueryClient;
}
{{else if (eq api "trpc")}}
export interface RouterAppContext {
  trpc: typeof trpc;
  queryClient: QueryClient;
}
{{else}}
export interface RouterAppContext {}
{{/if}}

export const Route = createRootRouteWithContext<RouterAppContext>()({
  component: RootComponent,
  head: () => ({
    meta: [
      {
        title: "{{projectName}}",
      },
      {
        name: "description",
        content: "{{projectName}} is a web application",
      },
    ],
    links: [
      {
        rel: "icon",
        href: "/favicon.ico",
      },
    ],
  }),
});

function RootComponent() {
  {{#if (eq api "orpc")}}
  const [client] = useState<AppRouterClient>(() => createORPCClient(link));
  const [orpcUtils] = useState(() => createTanstackQueryUtils(client));
  {{/if}}

  return (
    <>
      <HeadContent />
      {{#if (eq api "orpc")}}
        <ThemeProvider
          attribute="class"
          defaultTheme="dark"
          disableTransitionOnChange
          storageKey="vite-ui-theme"
        >
          <div className="grid grid-rows-[auto_1fr] h-svh">
            <Header />
            <Outlet />
          </div>
          <Toaster richColors />
        </ThemeProvider>
      {{else}}
      <ThemeProvider
        attribute="class"
        defaultTheme="dark"
        disableTransitionOnChange
        storageKey="vite-ui-theme"
      >
        <div className="grid grid-rows-[auto_1fr] h-svh">
          <Header />
          <Outlet />
        </div>
        <Toaster richColors />
      </ThemeProvider>
      {{/if}}
      <TanStackRouterDevtools position="bottom-left" />
      {{#if (or (eq api "orpc") (eq api "trpc"))}}
      <ReactQueryDevtools position="bottom" buttonPosition="bottom-right" />
      {{/if}}
    </>
  );
}
